//
//  KeChengDaGangViewController.m
//  ZhiBoYuan
//
//  Created by apple on 2018/4/17.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "KeChengDaGangViewController.h"
#import "BJFullScreenViewController.h"

#import <BJLiveUI/BJLiveUI.h>
#import <BJPlaybackUI/BJPlaybackUI.h>

//static NSString *ident = @"KeChengDaGangTableViewCell";
#import "KeChengDaGangTableViewCell.h"
#import "CourseOutlineModel.h"
#import "CourseChapterModel.h"
#import "CourseItem.h"

#import "BJYTokenModel.h"

#import "ToolHeader.h"

@interface KeChengDaGangViewController ()
<
UITableViewDataSource,
UITableViewDelegate
>

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic, strong)UILabel *startTimeLable;

@property (nonatomic,strong)UIView *headView;
@property (nonatomic,strong)UIButton *topButton;

@property (nonatomic,strong)CourseOutlineModel *outlineModel;

@property (nonatomic, assign)BOOL canScroll;


@end

@implementation KeChengDaGangViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    [self setTableView];
    

    [self downloadCourseDaGangDatas];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:TABLETOP object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:TABLELEAVETOP object:nil];
}
- (void)acceptMsg:(NSNotification *)notification
{
    NSString *notificationName = notification.name;
    if ([notificationName isEqualToString:TABLETOP])
    {
        NSDictionary *userInfo = notification.userInfo;
        NSString *can = userInfo[NotificationCanScroll];
        if ([can isEqualToString:@"1"])
        {
            self.canScroll = YES;
            self.tableView.showsVerticalScrollIndicator = YES;
        }
        
    }
    else if ([notificationName isEqualToString:TABLELEAVETOP])
    {
        self.canScroll = NO;
        self.tableView.showsVerticalScrollIndicator = NO;
        self.tableView.contentOffset = CGPointZero;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.canScroll)
    {
        [scrollView setContentOffset:CGPointZero];
    }
    CGFloat offSetY = scrollView.contentOffset.y;
    
    if (offSetY < 0)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:TABLELEAVETOP object:nil userInfo:@{NotificationCanScroll: @"1"}];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)setTableView{
    _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    //        tableView.backgroundColor = [UIColor greenColor];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [_tableView registerNib:[UINib nibWithNibName:@"KeChengDaGangTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"KeChengDaGangTableViewCell"];
    
    _tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
    
    _tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
        
    [_tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    
    [self.view addSubview:self.tableView];
}

- (void)startLearning{
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
        [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    }
}



- (void)downloadCourseDaGangDatas{
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       @"course_id":self.course_id// 1 直播 2微课 3套餐
                       };
    [SGHttpTool POST:Host_Append(CourseOutline) parameter:parameter sucess:^(id responseObject) {
        //成功回调
//        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
//        NSString *resultStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
//        ZYLog(@"22222434222 == %@",resultStr);
        
        NSLog(@"%@",responseObject);
        

        
        SGReceive *receive = [SGReceive receiveWithResponseObject:responseObject dataClass:[CourseOutlineModel class]];
        self.outlineModel = receive.data;
        
        [self setupConfigureView];
        
//        _startTimeLable.text = [NSString stringWithFormat:@"   开课时间:%@",[responseObject[@"data"] valueForKey:@"start_time"]];

        
        [self.dataArray addObjectsFromArray:self.outlineModel.chapter_list];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
    
}


- (void)setupConfigureView
{



    
    if ([self.outlineModel.start_time integerValue] <= 0)
    {

        self.tableView.sd_resetLayout
        .topSpaceToView(self.view, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .bottomSpaceToView(self.view, 0);
        
    }else{
        [self.view addSubview:self.headView];
        _startTimeLable.text = [NSString stringWithFormat:@"   开课时间:%@",self.outlineModel.start_time];
        self.headView.sd_layout
        .topSpaceToView(self.view, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 10)
        .heightIs(50);
        
        
        self.tableView.sd_layout
        .topSpaceToView(self.headView, 5)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .bottomSpaceToView(self.view, 0);

    }



}


-(UIButton *)topButton{
    if (!_topButton) {
        _topButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_topButton setBackgroundImage:[UIImage imageNamed:@"组3副本"] forState:(UIControlStateNormal)];
        BTN_MSG_FUNC(_topButton, topSender:);
        
    }
    return _topButton;
    
}

- (void)topSender:(UIButton *)sender {
    NSLog(@"返回顶部");
    
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

-(UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
        
        _startTimeLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
        
        _startTimeLable.text = @"   课程开始时间加载中。。。";
        
        _startTimeLable.backgroundColor =hui1Color;
        
        _startTimeLable.textColor = hui7Color;
        
        [_headView addSubview:_startTimeLable];
        
        
        
    }
    return _headView;
}


#pragma mark -- UITableViewDataSource,UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //    if (section == 0) {
    //        return 0;
    //    }
    return 40;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString * identy = @"head";
    
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    
    if (!hf) {
        
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
        
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width,40)];
        
        view.backgroundColor = hui1Color;
//        NSArray *arr = @[@"第一节 第一时 课程怎么学",@"第二节 第一时 课程怎么学广告专区",@"第三节 第一时 课程怎么学最近直播",@"第一节 第一时 课程怎么学热门直播"];
        CourseChapterModel *chapter = self.outlineModel.chapter_list[section];
        NSString *sectionTitle  = [NSString stringWithFormat:@"%@:%@",chapter.order_name,chapter.name] ;
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, self.view.frame.size.width-80, 40)];
        
        label.text = sectionTitle;
        
        [view addSubview:label];
        
        //        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        //
        //        button.tag = section + 100;
        //
        //        button.frame = CGRectMake(ScreenWidth-60, 0, 50, 40);
        //        [button setTitle:@"更多" forState:(UIControlStateNormal)];
        //
        //        BTN_MSG_FUNC(button, sender:);
        //
        //        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        //
        //        [view addSubview:button];
        
        
        [hf addSubview:view];
        
    }
    
    return hf;
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    CourseChapterModel *chapter = self.outlineModel.chapter_list[section];
    return chapter.child.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    KeChengDaGangTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KeChengDaGangTableViewCell" forIndexPath:indexPath];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    CourseChapterModel *chapter = self.outlineModel.chapter_list[indexPath.section];
    CourseItem *model = chapter.child[indexPath.row];
    cell.item = model;
//    cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
//    zjsDataBaseLesson *data = self.lessonArray[indexPath.row];
//    [cell loadData:data];
        
    return cell;
  
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return SNRealValue(50);
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"%@",ZYCurrentViewController());
    
    CourseChapterModel *chapter = self.outlineModel.chapter_list[indexPath.section];
    if (chapter.child.count == 0) {
        [MBProgressHUD showTextOnly:self.view message:@"暂无可学习内容" delay:2.0];
    }else{
        CourseItem *model = chapter.child[indexPath.row];
        [self requestVideoOAuthInfoForVid:model.itemID];
    }
    
    


}

#pragma mark -- 视频播放逻辑
- (void)requestVideoOAuthInfoForVid:(NSString *)chapter_id{
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       @"chapter_id":chapter_id// 1 直播 2微课 3套餐
                       };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];

    [SGHttpTool POST:Host_Append(VideoToken) parameter:parameter sucess:^(id responseObject) {
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];

        //成功回调
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString *resultStr =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        ZYLog(@"%@",resultStr);
        SGReceive *receive = [SGReceive receiveWithResponseObject:responseObject dataWord:@"chapter_info"dataClass:[BJYTokenModel class]];
//        self.outlineModel = receive.data;
        if ([receive.status intValue] == 200) {
            [self joinBJYVideoWithOAuthToken:receive.data chapterID:chapter_id];
        }else{
            [MBProgressHUD showTextOnly:[UIApplication sharedApplication].keyWindow message:receive.msg delay:2];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
    
}

- (void)joinBJYVideoWithOAuthToken:(BJYTokenModel *)info chapterID:(NSString *)chapterID{
    
    NSString *userName = [ZYUserManager userInfo].nick_name;
    NSString *userAvatar = [ZYUserManager userInfo].small_img;
    
    if ([info.type intValue] == 1) {//直播&回放
        if ([info.sub_type isEqualToString:@"zhibo"]) {//直播
            BJLRoomViewController *roomViewController = [BJLRoomViewController
                                                         instanceWithSecret:info.student_code
                                                         userName:userName
                                                         userAvatar:userAvatar];
            
            
            //  roomViewController.delegate = self;
            
            [ZYCurrentViewController() presentViewController:roomViewController animated:YES completion:nil];
        }else if ([info.sub_type isEqualToString:@"huifang"]){//回放
            BJPRoomViewController *vc = [BJPRoomViewController onlineVideoCreateRoomWithClassId:info.room_id sessionId:nil token:info.token userName:nil userNumber:0];
            [ZYCurrentViewController() presentViewController:vc animated:YES completion:nil];

            
        }
    }else if([info.type intValue] == 2){//点播
        BJFullScreenViewController *playerVC = [[BJFullScreenViewController alloc] initWithVid:info.video_id token:info.token isNeedAD:NO mayDrag:YES];
        __weak typeof(self) weakSelf = self;

        [playerVC setVideoFinishBlock:^{
            if (weakSelf.clickToAnswer) {
                weakSelf.clickToAnswer(chapterID);
            }
            
        }];
        
        [ZYCurrentViewController() presentViewController:playerVC animated:YES completion:nil];
    }
    
    

}


#pragma mark -- property
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
